<script setup lang="ts">
import type {baseResponse} from "@/api";
import {userBindPwdApi, userUpdatePwdApi, type userUpdatePwdType} from "@/api/user_api";
import {Message} from "@arco-design/web-vue";
import {reactive, ref} from "vue";

interface Props {
  visible: boolean
  pwdType: 1 | 2
}
const props = defineProps<Props>()
const emits = defineEmits(["update:visible", "ok"])

const pwdFormRef = ref()
const form = reactive<userUpdatePwdType>({
  "oldPwd": "",
  "pwd": "",
})

function cancel() {
  emits("update:visible", false)
}
async function pwdHandler() {
  const val = await pwdFormRef.value.validate()
  if (val) {
    return false
  }
  let res :baseResponse<string>
  if (props.pwdType === 1){
    res = await userBindPwdApi({
      pwd: form.pwd,
    })
  }else {
    res = await userUpdatePwdApi(form)
  }
  if (res.code) {
    Message.error(res.msg)
    return false
  }
  Message.success(res.msg)
  form.pwd = ""
  form.rePwd = ""
  form.oldPwd = ""
  emits("ok")
  emits("update:visible", false)
  return true
}

function rePwdValidator(value: any, callback: (error?: string) => void) {
  if (value !== form.pwd){
    callback("两次密码不一致")
    return
  }
}


</script>

<template>
  <a-modal :visible="props.visible"
           @cancel="cancel"
           :title="props.pwdType === 1 ? '绑定密码' : '修改密码'" :on-before-ok="pwdHandler">
    <a-form ref="pwdFormRef" :model="form">
      <a-form-item v-if="props.pwdType === 2" label="原密码" field="oldPwd" validate-trigger="blur"
                   :rules="{required: true}">
        <a-input-password v-model="form.oldPwd" placeholder="原密码"></a-input-password>
      </a-form-item>
      <a-form-item label="新密码" field="pwd" validate-trigger="blur" :rules="{required: true}">
        <a-input-password v-model="form.pwd" placeholder="新密码"></a-input-password>
      </a-form-item>
      <a-form-item label="确认密码" field="rePwd" validate-trigger="blur"
                   :rules="[{required: true}, {validator: rePwdValidator}]">
        <a-input-password v-model="form.rePwd" placeholder="确认密码"></a-input-password>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style  lang="less">

</style>